#include "CalibrationApp.h"
#include "pt.h"

module CalibrationAppP{

	uses {
		interface Boot;
		interface Timer<TMilli> as PeriodTimer;
		interface Timer<TMilli> as WaitTimer;
		interface Leds;
		interface GeneralIO as Pin1; // Processor
		interface GeneralIO as Pin2; // Sensors
		interface GeneralIO as Pin3; // Radio
		
		interface GeneralIO as GIO1; // set as input
		//interface GeneralIO as Pin4;
		//interface GeneralIO as Pin5;
		//interface GeneralIO as Pin6;
		
		interface EnergyState;
	}

} implementation{

	struct pt pt;
	uint8_t remaining = LIFETIME;

	event void Boot.booted(){
		call GIO1.makeInput();
		PT_INIT(&pt);
		call Pin1.makeOutput();
		call Pin2.makeOutput();
		call Pin3.makeOutput();
/*		call Pin4.makeOutput();
		call Pin5.makeOutput();
		call Pin6.makeOutput();*/
		call Pin1.set();
		call Pin2.set();
		call Pin3.set();
/*		call Pin4.set();
		call Pin5.set();
		call Pin6.set();*/
		call EnergyState.setState(ENERGY_STATE1);
		call PeriodTimer.startPeriodic(PERIOD);
	}

	PT_THREAD(wait()) {
		PT_BEGIN(&pt);
		
		call Leds.led0On();
		call Leds.led1On();
		call Pin1.clr();
		call Pin2.clr();
		call EnergyState.setState(ENERGY_STATE2);
		call WaitTimer.startOneShot(WAIT_PROCESSOR);
		PT_YIELD(&pt);

		call Pin1.set();
		call Leds.led0Off();
		call EnergyState.setState(ENERGY_STATE3);
		call WaitTimer.startOneShot(WAIT_SENSOR);
		PT_YIELD(&pt);

		call Pin1.clr();
		call Leds.led0On();
		call EnergyState.setState(ENERGY_STATE2);
		call WaitTimer.startOneShot(WAIT_PROCESSOR);
		PT_YIELD(&pt);
		
		call Pin2.set();
		call Pin3.clr();
		call Leds.led1Off();
		call Leds.led2On();
		call EnergyState.setState(ENERGY_STATE4);
		call WaitTimer.startOneShot(WAIT_PROCESSOR);
		PT_YIELD(&pt);
		
		call Pin1.set();
		call Leds.led0Off();
		call EnergyState.setState(ENERGY_STATE5);
		call WaitTimer.startOneShot(WAIT_RADIO);
		PT_YIELD(&pt);
		
		call Pin1.clr();
		call Leds.led0On();
		call EnergyState.setState(ENERGY_STATE4);
		call WaitTimer.startOneShot(WAIT_PROCESSOR);
		PT_YIELD(&pt);
		
		call Pin1.set();
		call Pin3.set();
		call Leds.led0Off();
		call Leds.led2Off();
		call EnergyState.setState(ENERGY_STATE1);
		//remaining--;
		
		PT_END(&pt);		
	}

	task void workTask() {
		if(remaining==0) {
			call PeriodTimer.stop();
			call Leds.led0On();
			call Leds.led1On();
			call Leds.led2On();	
		} else {
			wait();
		}
	}

	event void WaitTimer.fired(){
		post workTask();
	}

	event void PeriodTimer.fired(){
		post workTask();
	}
}